﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace dpruna.SharePoint
{
    public class LookupPageBase : LayoutsPageBase
    {
        #region Constants
        private const string DefaultSelectorControlPath = "~/_CONTROLTEMPLATES/ExtendedLookupField/MultiSelectPagedGridView.ascx";
        private const string OnDataSelectedScriptKey = "LookupPageOnDataSelectedScript";
        private const string DataKeyField = "ID";
        private const string QueryStringListParam = "List";
        private const string QueryStringFieldParam = "Field";
        private const string QueryStringTextElemParam = "TextElem";
        private const string QueryStringValElemParam = "ValElem";
        private const string QueryStringMultiSelectParam = "MultiSelect";
        private const string DefaultFieldName = "Title";

        private const string SelectDataJavascript =
            @"<script type=""text/javascript"" language=""javascript""> 
                function closePopup(textElem, valElem, val, text) {
                    var hasErrors = false;
                    try {
                        if (window.parent != null && window.parent.document.getElementById(textElem) != null) {
                            var lkpValue = window.parent.document.getElementById(valElem);
                            var lkpText = window.parent.document.getElementById(textElem);
                            lkpValue.value = val;
                            lkpText.value = text;
                        }
                        else {
                            var iFrames = window.parent.document.getElementsByTagName('iframe');
                            var parentIFrame;
                            for (i = 0; i < iFrames.length; i++) {
                                if (iFrames[i].src.indexOf('listform.aspx?PageType=') != -1) {
                                    parentIFrame = iFrames[i];
                                    break;
                                }
                            }
                            if (parentIFrame != null) {
                                var contentDoc = parentIFrame.contentDocument || parentIFrame.contentWindow.document;
                                var lkpValue = contentDoc.getElementById(valElem);
                                var lkpText = contentDoc.getElementById(textElem);
                                lkpValue.value = val;
                                lkpText.value = text;
                            }
                        }
                    }
                    catch (err) {
                        hasErrors = true
                        alert(err);
                    }
                    finally {
                        if (hasErrors)
                            window.frameElement.cancelPopup();
                            /* for a reason that I do not know SP.UI.DialogResult is undefined */
                            //SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
                        else
                            window.frameElement.commitPopup();
                            /* for a reason that I do not know SP.UI.DialogResult is undefined */
                            //SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);
                    }
                }
            </script>";
        #endregion

        #region Fields
        protected virtual string SelectorControlPath
        {
            get { return DefaultSelectorControlPath; }
        }
        protected virtual Guid ListID
        {
            get
            {
                var list = Request[QueryStringListParam];
                Guid listId;
                if (Helpers.TryParseGuid(list, out listId))
                    return listId;
#if DEBUG
                throw new InvalidOperationException("Invalid value for QueryString \"List\" param.");
#endif
            }
        }
        protected virtual string FieldName
        {
            get
            {
                var fieldName = Request[QueryStringFieldParam];
                if (String.IsNullOrEmpty(fieldName))
                    fieldName = DefaultFieldName;

                return fieldName;
            }
        }
        protected virtual string ParentElement
        {
            get
            {
                var parentElem = Request[QueryStringTextElemParam];

#if DEBUG
                if (String.IsNullOrEmpty(parentElem))
                    throw new InvalidOperationException("Invalid value for QueryString parameter parentElem.");
#endif

                return parentElem;
            }
        }
        protected virtual string ValElement
        {
            get
            {
                var valElem = this.Request[QueryStringValElemParam];

#if DEBUG
                if (String.IsNullOrEmpty(valElem))
                    throw new InvalidOperationException("Invalid value for QueryString parameter valElem.");
#endif
                return valElem;
            }
        }
        protected virtual bool AllowMultiSelect
        {
            get
            {
                var allowMultiSelectString = this.Page.Request[QueryStringMultiSelectParam];
                var allowMultiSelect = false;
                if (!String.IsNullOrEmpty(allowMultiSelectString))
                    allowMultiSelect = allowMultiSelectString == "1" ? true : false;

                return allowMultiSelect;
            }
        }
        #endregion

        #region Protected Methods
        protected override void OnInit(EventArgs e)
        {
            // make sure controls are created in order to participate in postback events
            EnsureChildControls();
        }
        protected override void CreateChildControls()
        {
            CreateFilterChildControls();

            if (Master == null)
                return;

            var pageHeadPlaceHolder = Master.FindControl("PlaceHolderAdditionalPageHead") as ContentPlaceHolder;
            if (pageHeadPlaceHolder != null)
                pageHeadPlaceHolder.Controls.Add(new LiteralControl { Text = SelectDataJavascript });
            

            var mainContentPlaceHolder = Master.FindControl("PlaceHolderMain") as ContentPlaceHolder;
            if (mainContentPlaceHolder != null)
            {
                var ctl = Page.LoadControl(SelectorControlPath) as MultiSelectPagedGridView;
                if (ctl == null)
                    return;

                ctl.ListID = ListID;
                ctl.DataKeyField = DataKeyField;
                ctl.AllowMultiSelect = AllowMultiSelect;
                ctl.FieldName = FieldName;
                ctl.DataSelected += CtlOnDataSelected;
                mainContentPlaceHolder.Controls.Add(ctl);
            }
        }
        /// <summary>
        /// Add filter controls that to filter the lookup page grid items
        /// </summary>
        /// <param name="e">Event arguments</param>
        protected virtual void CreateFilterChildControls()
        {

        }
        protected virtual void OnDataSelected(MultiSelectPagedGridViewSelectEventArgs args)
        {
            if (!
                Page.ClientScript.IsClientScriptBlockRegistered(OnDataSelectedScriptKey))
            {
                var dataSelectedScript = String.Format("closePopup('{0}', '{1}', '{2}', '{3}');", ParentElement,
                                                       ValElement, args.Ids, args.DisplayNames);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), OnDataSelectedScriptKey, dataSelectedScript, true);
            }
        }
        #endregion

        #region Private Methods
        private void CtlOnDataSelected(object sender, MultiSelectPagedGridViewSelectEventArgs multiSelectPagedGridViewSelectEventArgs)
        {
            OnDataSelected(multiSelectPagedGridViewSelectEventArgs);
        }
        #endregion
    }
}
